<?php

/** * 获取和设置配置参数 支持批量定义
 * @param string|array $name 配置变量
 * @param mixed $value 配置值
 * @param mixed $default 默认值
 * @return mixed
 */
function C($name=null, $value=null,$default=null) {
    static $_config = array();
    // 无参数时获取所有
    if (empty($name)) {
        return $_config;
    }
    // 优先执行设置获取或赋值
    if (is_string($name)) {
        if (!strpos($name, '.')) {
            $name = strtoupper($name);
            if (is_null($value))
                return isset($_config[$name]) ? $_config[$name] : $default;
            $_config[$name] = $value;
            return;
        }
        // 二维数组设置和获取支持
        $name = explode('.', $name);
        $name[0]   =  strtoupper($name[0]);
        if (is_null($value))
            return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
        $_config[$name[0]][$name[1]] = $value;
        return;
    }
    // 批量设置
    if (is_array($name)){
        $_config = array_merge($_config, array_change_key_case($name,CASE_UPPER));
        return;
    }
    return null; // 避免非法参数
}


//简单的打印调试函数
function dd($value) {
    echo "<pre>";
    var_dump($value);
    echo "</pre>";
    exit;
}

function p($value) {
    echo "<pre>";
    print_r($value);
    echo "</pre>";
    exit;
}

function assert_eq($val1, $val2) {
    var_dump($val1 === $val2);
}


function array_get($array, $key, $default = null)
{
    if (is_null($key)) return $array;

    // To retrieve the array item using dot syntax, we'll iterate through
    // each segment in the key and look for that value. If it exists, we
    // will return it, otherwise we will set the depth of the array and
    // look for the next segment.
    foreach (explode('.', $key) as $segment)
    {
        if ( ! is_array($array) or ! array_key_exists($segment, $array))
        {
            return value($default);
        }

        $array = $array[$segment];
    }

    return $array;
}


function str_contains($haystack, $needle)
{
    foreach ((array) $needle as $n)
    {
        if (strpos($haystack, $n) !== false) return true;
    }

    return false;
}


/**
 * 分割数组成含有键值数组的两个元素的数组
 *
 * @param  array  $array
 * @return array
 */
function array_divide($array)
{
    return array(array_keys($array), array_values($array));
}


function value($value)
{
    return (is_callable($value) and ! is_string($value)) ? call_user_func($value) : $value;
}


function with($object)
{
    return $object;
}


function array_first($array, $callback, $default = null)
{
    foreach ($array as $key => $value)
    {
        if (call_user_func($callback, $key, $value)) return $value;
    }

    return value($default);
}


function head($array)
{
    return reset($array);
}

function starts_with($haystack, $needle)
{
    return strpos($haystack, $needle) === 0;
}


function str_object($value)
{
    return is_object($value) and method_exists($value, '__toString');
}